package cn.car91.activity;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import cn.car91.R;
import cn.car91.adapter.ArticleListAdapter;
import cn.car91.adapter.ArticleSortListAdapter;
import cn.car91.bean.Article;
import cn.car91.bean.ArticleType;
import cn.car91.http.HttpHandler;
import cn.car91.pager.ArticlePager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.view.FooterView.Item;
import cn.car91.view.MyListView;
import cn.car91.view.VerticalScrollView;
import cn.car91.view.XListView;
import cn.car91.view.XListView.IXListViewListener;
import cn.car91.view.XListViewFooter;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

public class ArticleMainActivity extends BaseActivity {
    private ArticlePager articlePager = new ArticlePager();

    LayoutInflater mLayoutInflater;

    ImageButton moreButton = null;
    @ViewInject(R.id.navi_switcher_article)
    LinearLayout typeGroup;
    LinearLayout sortList = null;
    @ViewInject(R.id.article_list)
    XListView articleList;
    ArticleListAdapter articleListAdapter = null;
    ArticleSortListAdapter articleSortListAdapter = null;

    @ViewInject(R.id.none)
    View none = null;

    PopupWindow popupWindow = null;

    boolean addDate = false;
    int curatid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_article_main);
        super.onCreate(savedInstanceState);

        mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

        sortList = (LinearLayout) mLayoutInflater.inflate(R.layout.view_article_sort, null);
        sortList.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        sortList.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                closePopupWindow();
            }
        });
        articleSortListAdapter = new ArticleSortListAdapter(this);
        MyListView sortListView = (MyListView) ((VerticalScrollView) sortList.getChildAt(0)).getChildAt(0);
        sortListView.setAdapter(articleSortListAdapter);
        sortListView.setOnItemClickListener(onSortItemClick);

        articleListAdapter = new ArticleListAdapter(this, R.layout.view_article_item);
        articleList.setAdapter(articleListAdapter);

        typeGroup.setOnClickListener(onMoreSortClickListener);
        initPopupWindow();

        //scrollView.setOnTouchListener(onScrollTouchListener);
        articleList.setPullLoadEnable(true);
        articleList.setPullRefreshEnable(true);
        articleList.setXListViewListener(onArticleViewListener);

        registerReceiver(itemChangeBroadcastReceiver, new IntentFilter(MainFragmentActivity.naviAction));
   
        ((TextView) findViewById(R.id.header_text)).setText("养车百科");
    }

    private IXListViewListener onArticleViewListener = new IXListViewListener() {
        @Override
        public void onRefresh() {
            addDate = false;
            articlePager.reset();
            articleList.getmFooterView().setState(XListViewFooter.STATE_NORMAL);
            getData();
        }

        @Override
        public void onLoadMore() {
            addDate = true;
            getData();
        }
    };

    /**
     * 停止刷新，
     */
    private void onStopLoad() {
        articleList.stopRefresh();
        articleList.stopLoadMore();
        articleList.setRefreshTime("刚刚");
    }

    private void getData() {
        /*String key = SearchActivity.searchKey;
        if (RegexUtil.isNull(key)) {*/
            articlePager.getPublicData(curatid, callBackArticleList);
        /*} else {
            articlePager.getSearchData(key, callBackArticleList);
        }*/
    }

    private void getSort() {
    	HttpHandler.httpHandler.getArticleSorts(callBackArticleSort);
    }

    private RequestCallBack callBackArticleSort = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            List<ArticleType> articleTypes = Car91JsonUtil.getDTOList(arg0.result.toString(), ArticleType.class);
            ArticleType articleType = new ArticleType();
            articleType.setAtid(0);
            articleType.setName("全部保养知识");
            articleTypes.add(0, articleType);
            articleSortListAdapter.setData(articleTypes);
            articleSortListAdapter.notifyDataSetChanged();
        }
    };

    private RequestCallBack callBackArticleList = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            // TODO Auto-generated method stub
            onStopLoad();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            String json = arg0.result.toString();
            List<Article> articles = Car91JsonUtil.getDTOList(json, Article.class);
            onStopLoad();
            if (addDate) {
                if (articles.size() > 0) {
                    articleListAdapter.addData(articles);
                    articleListAdapter.notifyDataSetChanged();
                    addDate = true;
                    showTextWhenNone(false);
                } else {
                    articleList.getmFooterView().getmHintView().setText(getResources().getString(R.string.xlistview_footer_hint_nomore));
                }
            } else {
                if (articles.size() > 0) {
                    articleListAdapter.setData(articles);
                    articleListAdapter.notifyDataSetChanged();
                    addDate = true;
                    showTextWhenNone(false);
                } else {
                    addDate = false;
                    showTextWhenNone(true);
                }
            }
        }
    };

    private void showTextWhenNone(Boolean show) {
        if (show) {
            if (articleList.getVisibility() == View.VISIBLE) {
                articleList.setVisibility(View.GONE);
            }
            if (none.getVisibility() == View.GONE) {
                none.setVisibility(View.VISIBLE);
            }
        } else {
            if (articleList.getVisibility() == View.GONE) {
                articleList.setVisibility(View.VISIBLE);
            }
            if (none.getVisibility() == View.VISIBLE) {
                none.setVisibility(View.GONE);
            }
        }
    }

    @OnItemClick(R.id.article_list)
    public void onListItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
        String aid = String.valueOf(articleListAdapter.getArticleId(arg2-1));
        Intent intent = new Intent();
        intent.putExtra("aid", aid);
        intent.setClass(ArticleMainActivity.this, ArticleDetailActivity.class);
        startActivity(intent);
    }

    private OnItemClickListener onSortItemClick = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub
            for (int i = 0; i < articleSortListAdapter.getCount(); i++) {
                RadioButton radioButton = (RadioButton) arg0.getChildAt(i);
                radioButton.setChecked(false);
            }
            RadioButton radioButton = ((RadioButton) arg0.getChildAt(arg2));
            radioButton.setChecked(true);
            curatid = (int) arg3;
            articlePager.reset();
            addDate = false;
            getData();
            ((TextView) typeGroup.getChildAt(0)).setText(radioButton.getText());
            closePopupWindow();
        }
    };

    private OnClickListener onMoreSortClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            try {
                if (popupWindow != null) {
                    if (popupWindow.isShowing()) {
                        closePopupWindow();
                    } else {
                        openPopupWindow();
                    }
                }
            } catch (Exception e) {
            }
        }
    };

    private void openPopupWindow() {
        if (popupWindow != null)
            if (!popupWindow.isShowing()) {
                sortList.getChildAt(0).setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, articleList.getMeasuredHeight()));
                sortList.setPadding(0, (int) (getResources().getDimension(R.dimen.header_height) + typeGroup.getMeasuredHeight()), 0, 0);
                popupWindow.setContentView(sortList);
                popupWindow.showAtLocation(typeGroup.getRootView(), Gravity.TOP, 0, 0);
            }
    }

    private void closePopupWindow() {
    	try {
	        if (popupWindow != null)
	        	if(popupWindow.isShowing())
	                    popupWindow.dismiss();
		} catch (Exception e) {}
    }

    private void initPopupWindow() {
        popupWindow = new PopupWindow(sortList, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.area_popu_anim_style);
        popupWindow.setOutsideTouchable(true);
		//加了下面这行，onItemClick才好用
        popupWindow.setFocusable(true);
    }

    private BroadcastReceiver itemChangeBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            int item = arg1.getIntExtra("curItem", Item.CB_INDEX_repairshop);
            closePopupWindow();

            if (item == Item.CB_INDEX_exposure) {
                if (articleSortListAdapter.getCount() <= 0)
                    getSort();

                articlePager.reset();
                addDate = false;
                getData();
            } else {
                /*String searchItem = SearchActivity.item;
                if (searchItem!=null&&searchItem.equals("article")) {
                	SearchActivity.clearSearchInfo();
                }*/
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(itemChangeBroadcastReceiver);
        super.onDestroy();
    }
}
